<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form name="userform">
    用户名<input type="text" name="username">
    </br>
    密码<input type="text" name="password">
    </br>
    <input type="button" id="regBtn">注册</input>
</form>
<script>
    function serialize(form) {
        //把表单中的元素集合转换成数组
        var elements = Array.prototype.slice.call(form.elements);
        //循环数组
        var data = [];
        elements.forEach(function (element) {
            //先取出元素类型
            switch (element.type) {
                case 'submit':
                case 'cancel':
                case 'reset':
                    break;
                case 'text':
                    data.push(element.name + '=' + element.value);
            }
        });
        return data.join('&')
    }
    window.onload = function () {
        document.querySelector("#regBtn").addEventListener('click', function () {
            var xhr = new XMLHttpRequest();
            xhr.open('post', '/reg', true);
            xhr.responseType = 'text';
            xhr.onreadystatechange = function () {
                // xhr.status只要是2开头的就是成功
                if (4 == xhr.readyState && /2\d{2}/.test(xhr.status)) {
                    console.log(xhr.responseText)
                }
            };
            var data = serialize(document.querySelector('form'));
            xhr.send(data);
        })
    }


</script>
</body>
</html>